/*裁剪产量统计*/
import React from "react";
import Relay from "react-relay";
import Util from "../../../../util/Util"
import { Modal, Button, Input } from 'fly';
import { DatePicker, Table, Select, message } from 'antd';
import SaveProductionCensusMutation from '../mutation/SaveProductionCensus';
import SearchStyleNoMutation from '../mutation/SearchStyleNo';
import moment from 'moment';
moment.locale('zh-cn');
import '../css/style.css';
const Option = Select.Option;
const { MonthPicker, RangePicker } = DatePicker;

export default class Cut extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            productionType:'',
            visible: false,
            upTime:'',//上次更新时间
            dataSource: [{
                    orderId: '',
                    styleNo: '',
                    count: "",
                    color: '',
                    size: '',
            }],
            searchData:[],
            styleNoInx: '',
            loading: false,
            updateTime: '',
            groupId: null,//组ID
            workShopId: null
        }
        this.goodsJson = [];
        this.orderIdOption = [];
        this.enId = sessionStorage.getItem('enterpriseId');
        this.searchStyleNo = this.debounce(this.searchStyleNo, 400)
    }
    //关闭弹框回调
    hideModal = () => {
        this.goodsJson = [];
        this.orderIdOption = [];
        let dataSource = [{
            orderId: '',
            styleNo: '',
            count: "",
            color: '',
            size: '',
        }]
        this.setState({
            dataSource,
            searchData:[],
            styleNoInx: '',
            loading: false,
            updateTime: '',
        },()=>{
            this.setState({
                visible: false,
            })
        });
    }
    //日期修改
    dateChange = (date, dateString) => {
        this.setState({
            updateTime: dateString
        })
    }
    //表格增加一行
    handleAdd() {
        const { dataSource } = this.state;
        const newData = {
            orderId: '',
            styleNo: '',
            count: "",
            color: '',
            size: '',
        };
        dataSource.splice(dataSource.length, 0, newData )
        this.setState({
            dataSource
        });
    }
    //表格删除当前行
    onDelete(index) {
        const dataSource = [...this.state.dataSource];
        dataSource.splice(index, 1);

        this.setState({
            dataSource,
        });
    }
    //款号选择
    styleNosChange(i,value) {
        let searchData = this.state.searchData;
        let content = this.state.dataSource;
        let orderList = JSON.parse(searchData[value].orderList);
        content[i].styleNo = searchData[value].styleNo;
        content[i].orderId = orderList[0] || ''; 
        this.setState({
            styleNoInx: value,
            dataSource: content,
        })
        this.orderIdOption[i] = orderList ? orderList.map((v,i,ele)=>{
            return <Option value={v}>{v}</Option>
        }) : null
    }
    //订单编号选择
    orderIdsChange(i,value) {
        let content = this.state.dataSource;
        content[i].orderId = value;
        this.setState({
            dataSource: content
        })
    }
    //监听款号搜索输入
    searchStyleNo (i,value){
        if (value == '') {
            this.setState({
                searchData: [],
            })
        } else {
            Relay.Store.commitUpdate(
                new SearchStyleNoMutation({
                    enterpriseId: this.enId,
                    styleNo: value,
                }), {
                    onSuccess: (res) => {
                        let data = res.likeStyleNoByStyleNo.likeStyleNoByStyleNo;
                        if(data.errorCode==0){
                            this.setState({
                                searchData: JSON.parse(data.styleNoOrderList).slice(0,4),
                                // searchData:[{"psId":11,"styleNo":"aa","orderIds":["123123","555"]},{"psId":11,"styleNo":"aa3","orderIds":["123123","12313223"]}]
                            })
                        } else {
                            message.info(data.value)
                        }
                    }
                }
            );
        }
    }
    //文本输入，自动完成
    debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    InputChange(type,index,e) {
        let text = e.target.value;
        let content = this.state.dataSource;
        const reg = /^[1-9]\d{0,9}$/;
        if (type == 'size') {
            if (text.length > 10) {
                return;
            }
            content[index].size = text;
        } else if (type == 'color') {
            if (text.length > 10) {
                return;
            }
            content[index].color = text;
        } else if (type == 'count') {
            if (!reg.test(text) && text != ''){
                return;
            }
            content[index].count = text;
        }
        this.setState({
            dataSource: content
        })
    }

    save() {
        this.goodsJson = [];
        const { dataSource } = this.state;
        this.isRequire = 1;
        message.config({
            top: 30
        })
        if(this.state.updateTime == '') {
            message.warn('请检查必填项，填写完整数据');
            return;
        }
        dataSource && dataSource.length ? dataSource.map((v,i)=>{
            if (v.styleNo &&v.orderId && v.count ){
                let Json = {
                    styleNo: v.styleNo,
                    orderId: v.orderId,
                    color: v.color,
                    size: v.size,
                    count: v.count,
                }
                this.goodsJson.push(Json)
            } else if (!v.styleNo || !v.orderId || !v.count) {
                this.isRequire = 0;
            }
        }) : null
        this.goodsJson.length && this.isRequire == 1 ? this.saveReq() : message.warn('请检查必填项，填写完整数据');
    }
    saveReq() {
        Relay.Store.commitUpdate(
            new SaveProductionCensusMutation({
                workShop: this.state.workShopId,
                workGroup:this.state.groupId,
                enterpriseId:this.enId,
                productionType: this.state.productionType,
                time: JSON.stringify(Util.timeStamp(this.state.updateTime)),
                goodsJson: JSON.stringify(this.goodsJson),
            }), {
                onSuccess: (res) => {
                    let data = res.saveProductionCensus.saveProductionCensus;
                    if(data.errorCode==0){ 
                        message.success('数据更新成功');
                        this.setState({
                            dataSource: [{
                                orderId: '',
                                styleNo: '',
                                count: "",
                                color: '',
                                size: '',
                            }],
                            searchData:[],
                            styleNoInx: '',
                            loading: false,
                            updateTime: '',
                            visible: false,
                        });
                        this.goodsJson = [];
                        this.props.updateData()
                    } else {
                        message.error(data.value);
                        this.goodsJson = [];
                    }
                }
            }
        );
    }
    disabledDate(current) {
        // Can not select days before today and today
        return current && current.valueOf() > Date.now();
    };
    render() {
        const { searchData,styleNoInx } = this.state;
        const countType = ['數量','裁剪数','缝制数','后整数','包装数']
        const styleNoOption = searchData && searchData.length ? searchData.map((v,i)=>{
                return <Option value={i}>{v.styleNo}</Option>
            }) : null
        const columns = [
            {
                title: '款号',
                dataIndex: 'styleNo',
                render:(text, record, index) =>{
                    return (
                        <Select
                            showSearch
                            style={{width: 130 ,margin: '0 -16px'}}
                            className='order_creat_select'
                            value={this.state.dataSource[index].styleNo == '' ? '请输入款号' : this.state.dataSource[index].styleNo}
                            placeholder="请输入款号"
                            notFoundContent="暂无数据"
                            optionFilterProp="children"
                            onSearch={this.searchStyleNo.bind(this,index)}
                            onChange={this.styleNosChange.bind(this,index)}
                            getPopupContainer={()=> document.getElementsByClassName('fly-modal-body')[0] || document.body}
                        >
                            {styleNoOption || null}
                        </Select>
                    )
                }
            },
            {
                title: '订单编号',
                dataIndex: 'orderId',
                render:(text, record, index) =>{
                    return (
                        <Select
                            style={{width: 190 ,margin: '0 -24px'}}
                            value={this.state.dataSource[index].orderId == '' ? '选择订单' : this.state.dataSource[index].orderId}
                            className='order_creat_select'
                            placeholder="选择订单"
                            notFoundContent="暂无数据"
                            optionFilterProp="children"
                            onChange={this.orderIdsChange.bind(this,index)}
                            getPopupContainer={()=> document.getElementsByClassName('fly-modal-body')[0] || document.body}
                        >
                            {this.orderIdOption[index] || null}
                        </Select>
                    )
                }
            },
            {
                title: "颜色",
                dataIndex: 'color',
                render:(text,record,i)=>{
                    return <Input value={this.state.dataSource[i].color} onChange={this.InputChange.bind(this,'color',i)} style={{width: 130 ,margin: '0 -16px'}} placeholder="" />
                }
            },
            {
                title: "尺码",
                dataIndex: 'size',
                render:(text,record,i)=>{
                    return <Input value={this.state.dataSource[i].size} onChange={this.InputChange.bind(this,'size',i)} style={{width: 130 ,margin: '0 -16px'}} placeholder="" />
                }
            },
            {
                title: countType[this.state.productionType],
                dataIndex: 'count',
                render:(text,record,i)=>{
                    return <Input value={this.state.dataSource[i].count} onChange={this.InputChange.bind(this,'count',i)} style={{width: 130 ,margin: '0 -16px'}} placeholder="" />
                }
            },
            {
                title: "",
                dataIndex: 'opeater',
                render:(text,record,i)=>{
                    if (i == 0) {
                        return <span>
                                    <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>
                               </span>
                    } else {
                        return <span>
                                    <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>&nbsp;
                                    <a className="order_from_sp_minus" onClick={this.onDelete.bind(this,i)}></a>
                               </span>
                    }
                }
            }
        ];
        const data = [{
            name:'zhe',
            gender:'dgdf',
            email1:'eafk',
            email2:'eafk',
            email3:'eafk',
            email4:'eafk',
            email5:'eafk',
            email6:'eafk',
            email7:'eafk',
        }]
        return(
            <div ref={'statistics_com_modal'} className="statistics_com_modal">
                <Modal
                    title="更新数据"
                    visible={this.state.visible}
                    onOk={this.save.bind(this)}
                    onCancel={this.hideModal}
                    okText="确定"
                    cancelText="取消"
                    wrapClassName="statistics_com_modal_style"
                >
                    <p>
                        <span className="statistics_com_modal_update">更新数据：</span>
                        <DatePicker
                            disabledDate={this.disabledDate.bind(this)}
                            onChange={this.dateChange.bind(this)}
                            getCalendarContainer={()=>this.refs.statistics_com_modal || document.body}
                            value={this.state.updateTime !== '' && this.state.updateTime !== null ? moment(Util.dateFormat(this.state.updateTime), 'YYYY-MM-DD') : null}
                        />
                    </p>
                    <br/>
                    <Table columns={columns}
                           rowKey={record => record.gid}
                           dataSource={this.state.dataSource}
                           loading={this.state.loading}
                           className='order_table statistics_com_modal_table'
                           pagination={false}
                    />
                </Modal>
            </div>
        )
    }
}